package com.example.flowermall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.flowermall.entity.Collect;
import com.example.flowermall.mapper.CollectionMapper;
import com.example.flowermall.service.ICollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoman
 * @since 2023-10-24
 */
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collect> implements ICollectionService {
    @Autowired
    CollectionMapper collectionMapper;
    @Override
    public List<Collect> getByUserId(Integer userId) {
        LambdaQueryWrapper<Collect> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId,userId);
        queryWrapper.eq(Collect::getIsCollection,1);
        List<Collect> collects = collectionMapper.selectList(queryWrapper);
        return collects;
    }

    @Override
    public Collect addCollection(Collect collect) {
        collect.setCreateTime(LocalDateTime.now());
        LambdaQueryWrapper<Collect> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId,collect.getUserId());
        queryWrapper.eq(Collect::getProductId,collect.getProductId());
        Collect collect1 = collectionMapper.selectOne(queryWrapper);
        if (collect1==null){
            collect.setIsCollection(1);
            collectionMapper.insert(collect);
        }
        else {
            if(collect.getIsCollection()==1){
                collect1.setIsCollection(0);
            }
            else {
                collect1.setIsCollection(1);
            }
            collectionMapper.updateById(collect1);
        }
        return  collectionMapper.selectOne(queryWrapper);
    }
}


